package models

import (
	"strings"
	"time"

	"github.com/jinzhu/gorm"
)

type Device struct {
	ID             int64           `gorm:"column:id" json:"id"`
	HardwareId     string          `gorm:"column:hardware_id" json:"hardware_id"`
	ModelId        int64           `gorm:"column:model_id;" json:"model_id"`
	IsBind         int64           `gorm:"column:is_bind" json:"is_bind"`
	ReleaseDate    time.Time       `gorm:"column:release_date" json:"release_date"`
	StoreId        int64           `gorm:"column:store_id" json:"store_id"`
	Status         int64           `gorm:"column:status" json:"status"`
	CreateTime     time.Time       `gorm:"column:create_time" json:"create_time"`
	UpdateTime     time.Time       `gorm:"column:update_time" json:"update_time"`
	DeviceNumber   string          `gorm:"column:device_number" json:"device_number"`
	Alias          string          `gorm:"column:alias" json:"alias"`
	DeviceModel    *DeviceModel    `gorm:"ForeignKey:ModelId" json:"device_model,omitempty"`
	CommWeimaqis   []CommWeimaqi   `gorm:"many2many:device_modular;association_jointable_foreignkey:modular_id;"json:"comm_weimaqis"`
	CommLgzs       []CommLgz       `gorm:"many2many:device_modular;association_jointable_foreignkey:modular_id;"json:"comm_lgzs"`
	AndroidScreens []AndroidScreen `gorm:"many2many:device_modular;association_jointable_foreignkey:modular_id;"json:"andorid_screens"`
	DeviceModulars []DeviceModular `gorm:"ForeignKey:DeviceId" json:"device_modulars"`
}

func (this *Device) GetInfo(
	where map[string]interface{},
	table string,
) (
	device Device,
) {
	db := Db
	db = ParseWhere(db, where)
	db = this.BeforePreload(db, table)
	db.
		Table("device").
		Find(&device)
	return
}

func (this *Device) GetList(
	where map[string]interface{},
	pagination map[string]interface{},
	table string,
) (
	devices []Device,
	count int,
) {
	db := Db
	db = ParsePagination(db, pagination)
	db = ParseWhere(db, where)
	db = this.BeforePreload(db, table)
	db.
		Table("device").
		Count(&count).
		Find(&devices)

	return
}
func (this *Device) BeforePreload(result *gorm.DB, table string) *gorm.DB {
	if strings.Contains(table, "comm_weimaqi") {
		result = result.Preload("CommWeimaqis", "`device_modular`.`modular_type`=1")
	}
	if strings.Contains(table, "comm_lgz") {
		result = result.Preload("CommLgzs", "`device_modular`.`modular_type`=3")
	}
	if strings.Contains(table, "android_screen") {
		result = result.Preload("AndroidScreens", "`device_modular`.`modular_type`=2")
	}
	if strings.Contains(table, "device_modular") {
		result = result.Preload("DeviceModulars")
	}
	if strings.Contains(table, "device_model") {
		result = result.Preload("DeviceModel")
	}
	return result
}

// func (this *Device) GetMsg(where map[string]interface{}) *Device {
// 	db := Db
// 	db.Table("device").Where(where).Scan(this)
// 	return this
// }
